package com.yanyeori.okhttps.controller;

import cn.zhxu.okhttps.HTTP;
import cn.zhxu.okhttps.jackson.JacksonMsgConvertor;
import com.yanyeori.framework.core.model.WebResponse;
import com.yanyeori.framework.core.util.DigestUtil;
import com.yanyeori.framework.core.util.IdUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chenkuan
 * @since 2022/10/6 17:23
 */
@RestController
@RequestMapping("/httpController")
public class HttpController {

    private static final HTTP http = HTTP.builder()
            .baseUrl("http://127.0.0.1:9210")
            .addMsgConvertor(new JacksonMsgConvertor())
            .build();

    private static final HTTP http1 = HTTP.builder()
            .baseUrl("https://vcms-te.lotuscars.com.cn/vhms")
            .addMsgConvertor(new JacksonMsgConvertor())
            .build();

    @PostMapping("/upload")
    public WebResponse upload(@RequestPart("file") MultipartFile file, @RequestPart("fileInfo") Map<String, Object> map) throws IOException {
        Map<String, String> headers = new HashMap<>();
        headers.put("vhms-auth-appkey", "f598e0b0-4b60-11e7-8d67-ec8eb66821f7");
        headers.put("vhms-auth-nonce", IdUtil.randomUUID());
        headers.put("vhms-auth-timestamp", String.valueOf(System.currentTimeMillis()));
        headers.put("vhms-auth-sign", DigestUtil.sha256(headers.get("vhms-auth-appkey") + headers.get("vhms-auth-nonce") + headers.get("vhms-auth-timestamp")));

        map.put("logFileSize", String.valueOf(file.getSize() / 1024));
        map.put("logFileMD5", DigestUtil.md5(file.getInputStream()));

        String s = http.sync("/alarmEventLog")
                .addHeader(headers)
                .addFilePara("logFile", "zip", file.getOriginalFilename(), file.getInputStream())
                .addBodyPara(map)
                .post()
                .getBody()
                .toString();
        System.out.println(s);
        return WebResponse.ok();
    }
}
